package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private IBookService bookService;
    @PostMapping("/save")
    public Result save(@RequestBody Book obj) {
        bookService.save(obj);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Book obj) {
        bookService.updateById(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        bookService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book obj = bookService.getById(id);
        return Result.success(obj);
    }

    @GetMapping("/list")
    public Result list() {
        List<Book> list = bookService.list(new QueryWrapper<Book>().last("limit 100"));
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result search(@RequestParam(required = false) String bookNo,
                         @RequestParam(required = false) String name,
                         @RequestParam(required = false) String author,
                         @RequestParam(required = false) String category,
                         @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                         @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        IPage<Book> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (bookNo != null) {
            wrapper.like("book_no", bookNo);
        }
        if (name != null) {
            wrapper.like("name", name);
        }
        if (author != null) {
            wrapper.like("author", author);
        }
        if (category != null) {
            wrapper.like("category", category);
        }
        wrapper.orderByDesc("id");
        IPage<Book> bookIPage = bookService.page(page, wrapper);
        return Result.success(bookIPage);
    }
    //根据BookNo模糊搜索
    @GetMapping("/search")
    public Result search(@RequestParam(required = false) String bookNo) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (bookNo != null) {
            wrapper.like("book_no", bookNo);
        }
        List<Book> list = bookService.list(wrapper);
        return Result.success(list);
    }
}
